<template>
  <div>
    <van-nav-bar title="登录" left-arrow @click-left="$router.back()" />

    <!--
  登录表单
  点击登录按钮的时候，会触发submit事件
  -->
    <van-form @submit="login">
      <van-field
        required
        v-model="mobile"
        label="手机号"
        placeholder="请输入你的手机号"
        :rules="rules.mobile"
      />
      <van-field
        :required="false"
        v-model="code"
        label="验证码"
        placeholder="请输入验证码"
        :rules="rules.code"
      />

      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
        :disabled="isLoad"
        :loading="isLoad"
        loading-text="登陆中...">
          登录
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { userLogin } from '@/api/user'
import { mapMutations } from 'vuex'

export default {
  name: 'Login',

  data() {
    return {
      // 手机号
      mobile: '',
      // 验证码
      code: '',
      // 校验规则
      rules: {
        mobile: [
          { required: true, message: '手机号不能为空' },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '手机号码格式错误'
          }
        ],
        code: [
          { required: true, message: '验证码不能为空' },
          {
            pattern: /^\d{6}$/,
            message: '验证码格式错误'
          }
        ]
      },
      isLoad: false
    }
  },

  methods: {
    ...mapMutations('user', [
      'setToken'
    ]),
    // 校验通过后提交submit事件登陆
    async login() {
      try {
        // 直接用ajax发送请求
        // const res = await axios({
        //   method: 'POST',
        //   url: '/v1_0/authorizations',
        //   data: {
        //     mobile: this.mobile,
        //     code: this.code
        //   }
        // })

        // 将请求代码统一封装到api中，使用时导入
        this.isLoad = true
        const res = await userLogin(this.mobile, this.code)
        this.$toast.success('登陆成功')
        this.setToken(res.data)

        // 获取flag的值 ==> 如果有flag，使用back进行回退，不要使用push
        const flag = this.$route.query.flag
        if (flag) {
          return this.$router.back()
        }
        this.$router.push('/')
      } catch {
        this.$toast.success('登陆失败')
      }
      this.isLoad = false
    }
  }
}
</script>

<style lang="less" scoped></style>
